<template>
    <a-menu v-model:selectedKeys="state.selectedKeys" :items="menuItems" theme="dark" mode="inline" />
</template>

<script lang="ts" setup>
import Iconfont from '@/components/Iconfont';
import { RouterMeta } from '@/router/typing';
import { ItemType } from 'ant-design-vue';
import { RouteRecordRaw } from 'vue-router';

const router = useRouter();
const routes = router.getRoutes();

const state = reactive({
    openKeys: [],
    selectedKeys: [],
})

watch(
    router.currentRoute,
    () => {
        const matched = router.currentRoute.value.matched.concat();
        state.selectedKeys = matched.filter(r => r.name !== 'home').map(r => r.name);
        state.openKeys = matched.filter(r => r.path !== router.currentRoute.value.path).map(r => r.name);
    },
    {
        immediate: true,
    }
)

// 路由转成菜单
const menuItems = computed(() => {
    const leftMenuRoutes = routes.find(o => o.name == 'home');
    const toMenuTree = (route: RouteRecordRaw) => {
        const meta = route.meta as unknown as RouterMeta
        const icon = meta.icon! ? h(Iconfont, { type: meta.icon }) : null
        const childrens = route.children

        let menu: ItemType = {
            label: meta.title,
            key: (route.name as string),
            icon: icon,
            children: childrens ? [] : null,
            onClick: () => router.push(route.path)
        }

        if (childrens) {
            for (const item of childrens) {
                const m = toMenuTree(item)
                menu.children.push(m)
            }
        }
        return menu
    }
    return toMenuTree(leftMenuRoutes).children ?? []
})
</script>